package com.nl.lib_core.tool

import android.annotation.SuppressLint
import android.content.Context
import android.view.Gravity
import android.widget.Toast
import com.nl.lib_core.BaseApplication
import com.nl.lib_core.tool.log.KLog

/** 作者: wangfei 创建时间: 2021/9/1 包名: com.nl.lib_core.util 类名: ToastUtil */
object ToastUtil {

  @JvmField var isShow = true

  @JvmField var messageOld: String? = null

  @JvmField var time: Long = 0

  @JvmField @Volatile var toast: Toast? = null

  /**
   * 短时间显示Toast
   * @param context
   * @param message 显示字符串
   * @param gravity 显示位置
   */
  fun showShort(context: Context?, message: CharSequence, gravity: Int) {
    showToast(context, message, gravity, Toast.LENGTH_SHORT)
  }

  /**
   * 短时间显示Toast
   * @param context
   * @param message 显示字符串
   * @param gravity 显示位置
   * @param duration 持续时间
   */
  @SuppressLint("ShowToast")
  fun showToast(context: Context?, message: CharSequence, gravity: Int, duration: Int) {
    val mContext = context ?: BaseApplication.instance
    if (isShow) {
      cancel()
      toast = Toast.makeText(mContext, message, duration)
      toast?.setGravity(gravity, 0, 0)
      toast?.show()
    }
  }

  /**
   * 短时间显示Toast
   * @param context
   * @param message 显示字符串
   */
  fun showShort(message: CharSequence) {
    showShort(null, message, Gravity.BOTTOM)
  }

  fun showShort(context: Context?, message: CharSequence) {
    showShort(context, message, Gravity.BOTTOM)
  }

  fun showShort(ResId: Int) {
    BaseApplication.instance?.resources?.let {
      showShort(null, it.getString(ResId), Gravity.BOTTOM)
    }
  }

  /**
   * 短时间显示Toast
   * @param context
   * @param message 显示字符串
   */
  fun showShortCenter(message: CharSequence) {
    showShort(null, message, Gravity.CENTER)
  }

  /**
   * 长时间Toast
   * @param context
   * @param message 显示字符串
   */
  fun showCenterLong(message: CharSequence) {
    showToast(null, message, Gravity.CENTER, Toast.LENGTH_LONG)
  }

  /**
   * 长时间Toast
   * @param context
   * @param message 显示字符串
   */
  fun showShortLong(context: Context?, message: CharSequence) {
    showToast(context, message, Gravity.BOTTOM, Toast.LENGTH_LONG)
  }

  fun cancel() {
    if (toast != null) {
      toast?.cancel()
      toast = null
    }
  }
}

fun myLog(any: Any){
  KLog.d("日志","$any")
}
